<template>
  <!-- 承包商项目管理 -->
  <div class="relatedpartyproject">
    <basic-container>
      <avue-crud
        :option="option"
        :table-loading="loading"
        :data="data"
        :page.sync="page"
        :permission="permissionList"
        :before-open="beforeOpen"
        v-model="form"
        ref="crud"
        @row-update="rowUpdate"
        @row-save="rowSave"
        @row-del="rowDel"
        @search-change="searchChange"
        @search-reset="searchReset"
        @selection-change="selectionChange"
        @current-change="currentChange"
        @size-change="sizeChange"
        @refresh-change="refreshChange"
        @on-load="onLoad"
      >

        <!-- 左上方菜单栏 -->
        <template slot="menuLeft">
          <el-button
            type="danger"
            size="small"
            icon="el-icon-delete"
            plain
            v-if="permission.relatedpartyproject_delete"
            @click="handleDelete">
            删 除
          </el-button>
        </template>

        <!-- 商务合同自定义 -->
        <template slot="swhtForm">
          <div>
            <el-upload
              v-if="dialogType !== 'view'"
              action="/api/fileManager/upload/file"
              :headers="SetHeaders"
              :file-list="swhtFileList"
              :before-upload="beforeUploadSWHT"
              :on-remove="handleRemoveSWHT"
              :on-success="uploadSWHTSuccess"
            >
              <el-button size="small" type="primary" icon="el-icon-document">选择文件</el-button>
            </el-upload>

            <a
              v-else
              v-for="(item, index) in swhtFileList"
              :key="index"
              :href="downloadHead + item.response.data.id"
              style="color:#409EFF"
            >
              <i class="el-icon-download" style="margin-right:5px;"></i>下载文件（{{ item.name }}）
            </a>
          </div>
        </template>

        <!-- 安全合同自定义 -->
        <template slot="aqthForm">
          <div>
            <el-upload
              v-if="dialogType !== 'view'"
              action="/api/fileManager/upload/file"
              :headers="SetHeaders"
              :file-list="aqthFileList"
              :before-upload="beforeUploadAQTH"
              :on-remove="handleRemoveAQTH"
              :on-success="uploadAQTHSuccess"
            >
              <el-button size="small" type="primary" icon="el-icon-document">选择文件</el-button>
            </el-upload>

            <a
              v-else
              v-for="(item, index) in aqthFileList"
              :key="index"
              :href="downloadHead + item.response.data.id"
              style="color:#409EFF"
            >
              <i class="el-icon-download" style="margin-right:5px;"></i>下载文件（{{ item.name }}）
            </a>
          </div>
        </template>

        <!-- 施工方案自定义 -->
        <template slot="sgfaForm">
          <div>
            <el-upload
              v-if="dialogType !== 'view'"
              action="/api/fileManager/upload/file"
              :headers="SetHeaders"
              :file-list="sgfaFileList"
              :before-upload="beforeUploadSGFA"
              :on-remove="handleRemoveSGFA"
              :on-success="uploadSGFASuccess"
            >
              <el-button size="small" type="primary" icon="el-icon-document">选择文件</el-button>
            </el-upload>

            <a
              v-else
              v-for="(item, index) in sgfaFileList"
              :key="index"
              :href="downloadHead + item.response.data.id"
              style="color:#409EFF"
            >
              <i class="el-icon-download" style="margin-right:5px;"></i>下载文件（{{ item.name }}）
            </a>
          </div>
        </template>

      </avue-crud>
    </basic-container>
  </div>
</template>

<script>
import {
  getList,
  getDetail,
  add,
  update,
  remove
} from "@/api/basedata/interestedpartymange/relatedpartyproject";
import { mapGetters } from "vuex";
import { getToken } from "@/util/auth";

export default {
  data() {
    return {
      form: {},
      query: {},
      data: [],
      loading: true,
      selectionList: [],
      page: {
        pageSize: this.$pageSize,
        currentPage: 1,
        total: 0
      },
      option: {
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchSpan: 5,
        searchMenuSpan: 4,
        border: true,
        index: false,
        selection: true,
        viewBtn: true,
        refreshBtn: true,
        columnBtn: false,
        dialogClickModal: false,
        menuWidth: 200,
        column: [
          {
            label: "项目类型",
            prop: "xmlx",
            align: "center",
          },
          {
            label: "项目名称",
            prop: "xmmc",
            align: "center",
            rules: [{
              required: true,
              message: "请输入项目名称",
              trigger: "blur"
            }]
          },
          {
            label: "项目内容",
            prop: "fwxmnr",
            align: "center",
            span: 24,
            type: "textarea",
            maxlength: 150
          },
          {
            label: "项目负责人",
            prop: "xmfzr",
            align: "center",
          },
          {
            label: "项目资金",
            prop: "xmhtzj",
            align: "center",
            width: 120,
            type: "number",
            precision: 0,
            minRows: 1,
            step: 1,
          },
          {
            label: "开始时间",
            prop: "kssj",
            align: "center",
            width: 120,
            type: "date",
            format: "yyyy-MM-dd",
            valueFormat: "yyyy-MM-dd"
          },
          {
            label: "结束时间",
            prop: "jssj",
            align: "center",
            width: 120,
            type: "date",
            format: "yyyy-MM-dd",
            valueFormat: "yyyy-MM-dd"
          },
          {
            label: "承包商",
            prop: "relatedPartyId",
            hide: true,
            type: "select",
            dicUrl: "/api/interestedPartyMange/relatedparty/list",
            props: {
              label: "dwmc",
              value: "id",
            },
          },
          {
            label: "商务合同",
            prop: "swht",
            span: 24,
            hide: true,
            formslot: true
          },
          {
            label: "安全合同",
            prop: "aqth",
            span: 24,
            hide: true,
            formslot: true
          },
          {
            label: "施工方案",
            prop: "sgfa",
            span: 24,
            hide: true,
            formslot: true
          }
        ]
      },
      // 商务合同
      dialogType: "",
      downloadHead: "/api/fileManager/download/",
      swhtFileList: [],
      SetHeaders: { "Blade-Auth": getToken() },
      // 安全合同
      aqthFileList: [],
      // 施工方案
      sgfaFileList: [],
    };
  },
  computed: {
    ...mapGetters(["permission"]),

    // 按钮权限
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.relatedpartyproject_add, false),
        viewBtn: this.vaildData(this.permission.relatedpartyproject_view, false),
        delBtn: this.vaildData(this.permission.relatedpartyproject_delete, false),
        editBtn: this.vaildData(this.permission.relatedpartyproject_edit, false)
      };
    },

    // 勾选项ID
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(",");
    }
  },
  methods: {

    // 新增
    rowSave(row, done, loading) {
      add(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        },
        error => {
          loading();
          window.console.log(error);
        }
      );
    },

    // 修改
    rowUpdate(row, index, done, loading) {
      update(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        },
        error => {
          loading();
          console.log(error);
        }
      );
    },

    // 删除一条
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        });
    },

    // 删除多条
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.$refs.crud.toggleSelection();
        });
    },

    // 打开新增、修改、查看弹窗前
    beforeOpen(done, type) {
      this.dialogType = type;
      this.swhtFileList = [];
      this.aqthFileList = [];
      this.sgfaFileList = [];
      if (["edit", "view"].includes(type)) {
        getDetail(this.form.id).then(res => {
          this.form = res.data.data;
          if (this.form.swht && this.form.swhtFile && JSON.stringify(this.form.swhtFile) !== "{}") {
            this.swhtFileList.push({
              name: this.form.swhtFile.fileName,
              response: {
                code: 200,
                msg: "操作成功",
                success: true,
                data: this.form.swhtFile
              }
            });
          }
          if (this.form.aqth && this.form.aqthFile && JSON.stringify(this.form.aqthFile) !== "{}") {
            this.aqthFileList.push({
              name: this.form.aqthFile.fileName,
              response: {
                code: 200,
                msg: "操作成功",
                success: true,
                data: this.form.aqthFile
              }
            });
          }
          if (this.form.sgfa && this.form.sgfaFile && JSON.stringify(this.form.sgfaFile) !== "{}") {
            this.sgfaFileList.push({
              name: this.form.sgfaFile.fileName,
              response: {
                code: 200,
                msg: "操作成功",
                success: true,
                data: this.form.sgfaFile
              }
            });
          }
        });
      }
      done();
    },

    // 清空搜索条件
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },

    // 搜索条件改变
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },

    // 勾选
    selectionChange(list) {
      this.selectionList = list;
    },

    // 清空勾选
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },

    // 更换页数
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },

    // 更换每页显示数量
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },

    // 刷新
    refreshChange() {
      this.onLoad(this.page, this.query);
    },

    // 加载数据
    onLoad(page, params = {}) {
      this.loading = true;
      getList(
        page.currentPage,
        page.pageSize,
        Object.assign(params, this.query)
      ).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },

    /**
     * 上传商务合同
     */

    // 上传商务合同前
    beforeUploadSWHT(file) {
      console.log(file);
      var isLimit = this.swhtFileList.length + 1 <= 1;
      if (!isLimit) {
        this.$message.warning("只能选择一个商务合同!");
      }
      return isLimit;
    },

    // 上传商务合同成功
    uploadSWHTSuccess(response, file, fileList) {
      if (response.code !== 200 || response.success !== true) {
        return;
      }
      this.swhtFileList = fileList;
      this.form.swht = this.formatFJ(this.swhtFileList);
    },

    // 删除商务合同
    handleRemoveSWHT(file, fileList) {
      this.swhtFileList = fileList;
      this.form.swht = this.formatFJ(this.swhtFileList);
    },

    // 格式化附件ID
    formatFJ(fileList) {
      var ids = [];
      fileList.forEach(item => {
        ids.push(item.response.data.id);
      });
      return ids.join(",");
    },

    /**
     * 上传安全合同
     */

    // 上传安全合同前
    beforeUploadAQTH(file) {
      console.log(file);
      var isLimit = this.aqthFileList.length + 1 <= 1;
      if (!isLimit) {
        this.$message.warning("只能选择一个安全合同!");
      }
      return isLimit;
    },

    // 上传安全合同成功
    uploadAQTHSuccess(response, file, fileList) {
      if (response.code !== 200 || response.success !== true) {
        return;
      }
      this.aqthFileList = fileList;
      this.form.aqth = this.formatFJ(this.aqthFileList);
    },

    // 删除安全合同
    handleRemoveAQTH(file, fileList) {
      this.aqthFileList = fileList;
      this.form.aqth = this.formatFJ(this.aqthFileList);
    },

    /**
     * 上传施工方案
     */

    // 上传施工方案前
    beforeUploadSGFA(file) {
      console.log(file);
      var isLimit = this.sgfaFileList.length + 1 <= 1;
      if (!isLimit) {
        this.$message.warning("只能选择一个施工方案!");
      }
      return isLimit;
    },

    // 上传施工方案成功
    uploadSGFASuccess(response, file, fileList) {
      if (response.code !== 200 || response.success !== true) {
        return;
      }
      this.sgfaFileList = fileList;
      this.form.sgfa = this.formatFJ(this.sgfaFileList);
    },

    // 删除施工方案
    handleRemoveSGFA(file, fileList) {
      this.sgfaFileList = fileList;
      this.form.sgfa = this.formatFJ(this.sgfaFileList);
    }

  }
};
</script>

<style></style>